package com.ts.api.module.match.plan.internal.distribute.context;

import com.gitee.apanlh.util.base.ChooseOr;
import com.ts.api.common.constant.product.ProductPlanVersionMode;
import com.ts.api.module.product.entity.po.ProductPO;
import com.ts.api.module.product.entity.po.ProductPlanPO;
import com.ts.api.module.product.service.ProductPlanTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *  计划分发上下文
 *
 *  @author Pan
 */
@Component
public class PlanDistributeContext {

    @Autowired
    private ProductPlanTypeService productPlanTypeService;

    /**
     *  获取分发类型
     *
     *  @param  productPO           主体实体
     *  @param  productPlanPO       主体计划实体
     *  @return PlanDistributeType
     */
    public PlanDistributeType getDistributeType(ProductPO productPO, ProductPlanPO productPlanPO) {
        Integer planVersionMode = productPlanPO.getVersionMode();
        //  计划类型
        boolean hasLocalOrgPlan = productPlanTypeService.hasLocalOrgPlan(productPO, productPlanPO);
        boolean hasApiOrgPlan = productPlanTypeService.hasApiOrgPlan(productPO, productPlanPO);
        boolean hasPlatformPlan = productPlanTypeService.hasPlatformPlan(productPlanPO);
        boolean hasLocalSpecialPlan = productPlanTypeService.hasLocalSpecialPlan(productPO, productPlanPO);
        boolean hasApiSpecialPlan = productPlanTypeService.hasApiSpecialPlan(productPO, productPlanPO);

        //  计划模式
        boolean hasMd5Mode = ProductPlanVersionMode.MD5.hasVersionMode(planVersionMode);
        boolean hasPhoneMask8Mode = ProductPlanVersionMode.PHONE_MASK_8.hasVersionMode(planVersionMode);

        //  首次获取本地计划
        PlanDistributeType planDistributeType = ChooseOr.create(hasLocalOrgPlan, () -> PlanDistributeType.LOCAL_ORG)
            //  计划机构
            .orElseIf(hasApiOrgPlan && hasMd5Mode, () -> PlanDistributeType.API_ORG_PHONE_MD5)
            .orElseIf(hasApiOrgPlan && hasPhoneMask8Mode, () -> PlanDistributeType.API_ORG_PHONE_MASK)

            //  平台计划
            .orElseIf(hasPlatformPlan && hasMd5Mode, () -> PlanDistributeType.API_PLAT_FORM_PHONE_MD5)
            .orElseIf(hasPlatformPlan && hasPhoneMask8Mode, () -> PlanDistributeType.API_PLAT_FORM_PHONE_MASK)

            //  特殊计划
            .orElseIf(hasLocalSpecialPlan, () -> PlanDistributeType.LOCAL_SPECIAL)
            .orElseIf(hasApiSpecialPlan && hasMd5Mode, () -> PlanDistributeType.API_SPECIAL_PHONE_MD5)
            .orElseIf(hasApiSpecialPlan && hasPhoneMask8Mode, () -> PlanDistributeType.API_SPECIAL_PHONE_MASK)
        .getChoose();
        return planDistributeType;
    }
}
